<template>
  <div>
    <h1>用来显示用户列表的组件</h1>
    <el-table
      :data="users.filter(data => !search || data.username.toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%">
      <el-table-column label="编号" width="180" prop="id"></el-table-column>
      <el-table-column label="姓名" width="180" prop="username"></el-table-column>
      <el-table-column label="生日" width="180" prop="birthday"></el-table-column>
      <el-table-column label="性别" width="180" prop="gender"></el-table-column>
      <el-table-column label="家庭住址" width="180" prop="address"></el-table-column>
      <el-table-column align="right" width="180">
        <template slot="header" slot-scope="scope">
          <el-input
            v-model="search"
            size="mini"
            placeholder="输入姓名的关键字搜索"/>
        </template>
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>

          <el-popconfirm
            title="确定要删除这个用户吗？"
            @confirm="handleDelete(scope.$index, scope.row)"
            confirm-button-text="好的"
            cancel-button-text="不用"
            confirm-button-type="danger"
            cancel-button-type="success"
          >
            <el-button
              slot="reference"
              size="mini"
              type="danger">删除
            </el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <el-row>
      <el-col :span="3">
        <el-button type="primary" size="mini" @click="addUser" style="margin-top: 20px">添加用户</el-button>
      </el-col>
      <el-col :span="21">
        <el-pagination background
                       layout="prev, pager, next, total, sizes, jumper"
                       :total="total"
                       :page-size="pageSize"
                       :page-sizes="[2,5,10]"
                       style="margin-top: 20px"
                       prev-text="上一页"
                       next-text="下一页"
                       @current-change="getCurrentPage"
                       @size-change="getCurrentSize"
        >
        </el-pagination>
      </el-col>
    </el-row>

    <transition name="el-fade-in-linear">
      <div v-show="show" class="transition-box">
        <el-form ref="userForm" :model="form" label-width="80px" :rules="rules">
          <el-form-item label="姓名" prop="username"> <!--pro表示要校验的属性-->
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="生日" prop="birthday">
            <el-date-picker type="date" placeholder="选择日期" v-model="form.birthday"
                            style="width: 100%;"></el-date-picker>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="form.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="家庭住址">
            <el-input type="textarea" v-model="form.address"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">确认</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>
  </div>
</template>
<script>
import moment from "moment";

export default {
  data() {
    return {
      search: "",
      users: [],
      show: false,
      total: 0,
      currentPage: 1,
      pageSize: 5,
      form: {
        username: '',
        birthday: '',
        gender: 1,
        address: '',
      },
      rules: {
        username: [
          {required: true, message: '请输入用户的姓名', trigger: 'blur'},
        ],
        birthday: [
          {required: true, message: '请输入用户的生日', trigger: 'blur'},
        ]
      }
    };

  },
  methods: {
    getCurrentSize(size) {
      this.pageSize = size;
      this.listUser(this.currentPage, size);
    },
    getCurrentPage(page) {
      this.currentPage = page;
      this.listUser(page, this.pageSize);
    },
    reset() {
      this.form = {gender: 1}
    },
    handleEdit(index, row) {
      // 只对副本操作
      let rowData = Object.assign({}, row); //浅拷贝，对于基本类型来说就是深拷贝，也就是副本和原始对象的属性值互不影响
      this.show = true;
      this.form = rowData;
      this.form.gender = rowData.gender === '男' ? 1 : 2;
    },
    handleDelete(index, row) {
      this.$http.delete("http://localhost:8888/elementUi/elementUser?id=" + row.id)
        .then(resp => {
          if (resp.data.code === 200) {
            this.$message.success("删除成功");
          }
          this.listUser();
        }).catch(err => {
        console.error(err);
        this.$message.error("小招开小差了，请稍后再试...");
      })
    },
    addUser() {
      this.show = !this.show;
      this.form = {gender: 1}
    },
    listUser() {
      this.$http.get("http://localhost:8888/elementUi/elementUser/pageListUser?currentPage=" + this.currentPage + "&pageSize=" + this.pageSize)
        .then(res => {
          if (res.data.code === 200) {
            let respData = res.data.data;
            this.users = respData.data;
            this.users.forEach(user => {
              user.gender = user.gender === 1 ? '男' : '女';
            });
            this.total = respData.total;
          }
        }).catch(err => {
        console.error(`发生了异常：${err}`);
      });
    },
    onSubmit() {
      this.$refs.userForm.validate((valid) => {
        if (!valid) {
          console.log("表单输入的数据不合法！");
          return false;
        }
        let birth = this.form.birthday;
        this.form.birthday = moment(birth).format("YYYY-MM-DD");
        this.$http.post(
          "http://localhost:8888/elementUi/elementUser",
          this.form,
          {
            headers: {"Content-Type": "application/x-www-form-urlencoded"}
          })
          .then(res => {
            if (res.data.code === 200) {
              this.$message({
                message: res.data.message,
                type: 'success'
              });
            } else {
              this.$message.error(res.data.message);
            }
            this.form = {gender: 1};
            this.show = false;
            this.listUser();
          });
      });
    },
  },
  created() {
    this.listUser();
  }
}
</script>
<style>
.transition-box {
  margin-top: 20px;
  margin-bottom: 10px;
  width: 500px;
  height: 400px;
  border-radius: 4px;
  padding: 40px 20px;
  box-sizing: border-box;
  margin-right: 20px;
}
</style>
